<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>城乡居民基本养老保险个人账户计算器</title>
    <!-- 引入 Element Plus 样式 -->
    <link href="https://unpkg.com/element-plus/dist/index.css" rel="stylesheet">
    <style>
        .guide-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }
        .clickable-card {
            cursor: pointer;
        }
        .clickable-link {
            cursor: pointer;
            text-decoration: none;
            color: inherit;
        }
        .el-header, .el-footer {
            text-align: center;
            line-height: 60px;
        }
        .el-main {
            text-align: center;
            line-height: 160px;
        }
        body > .el-container {
            margin-bottom: 40px;
        }
        .el-container:nth-child(5) .el-aside,
        .el-container:nth-child(6) .el-aside {
            line-height: 260px;
        }
        .el-container:nth-child(7) .el-aside {
            line-height: 320px;
        }
        /* 小屏幕（手机）样式 */
        @media (max-width: 768px) {
            .el-header, .el-footer {
                line-height: 40px;
            }
            .el-main {
                line-height: normal;
            }
            .el-col {
                margin-bottom: 10px;
            }
            .el-table-column {
                padding: 5px;
            }
            .el-button {
                width: 100%;
                margin-bottom: 10px;
            }
            .el-input, .el-select {
                width: 100%;
            }
        }
        /* 大屏幕（PC）样式 */
        @media (min-width: 769px) {
            .el-header, .el-footer {
                line-height: 60px;
            }
            .el-main {
                line-height: 160px;
            }
            .el-col {
                margin-bottom: 0;
            }
            .el-table-column {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <el-tabs v-model="form.activeName">
        <el-tab-pane label="城乡居民养老保险计算器" name="first">
            <el-row>
                <el-col :span="16">
                    <el-container>
                        <el-header>{{form.userName != '' ? ('正在推算...' + form.userName + ' ') : ''}}个人账户收入计算</el-header>
                        <el-container>
                            <el-main>
                                <el-form :model="form">
                                    <el-form-item label="缴费档次">
                                        <el-radio-group v-model="form.grade">
                                            <el-radio-button label="100">100元</el-radio-button>
                                            <el-radio-button label="120">120元</el-radio-button>
                                            <el-radio-button label="180">180元</el-radio-button>
                                            <el-radio-button label="240">240元</el-radio-button>
                                            <el-radio-button label="360">360元</el-radio-button>
                                            <el-radio-button label="480">480元</el-radio-button>
                                            <el-radio-button label="540">540元</el-radio-button>
                                            <el-radio-button label="600">600元</el-radio-button>
                                            <el-radio-button label="900">900元</el-radio-button>
                                            <el-radio-button label="1200">1200元</el-radio-button>
                                            <el-radio-button label="1800">1800元</el-radio-button>
                                            <el-radio-button label="3600">3600元</el-radio-button>
                                            <el-radio-button label="4800">4800元</el-radio-button>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-row :gutter="10" class="mb8">
                                            <el-col :span="1.5">
                                                <el-button @click="addYear" type="primary">添加年度</el-button>
                                            </el-col>
                                            <el-col :span="1.5">
                                                <el-button @click="resetData" type="danger">重 置</el-button>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </el-form>
                                <el-table :data="tableData" style="width: 100%">
                                    <el-table-column label="操作">
                                        <template #default="{ row }">
                                            <el-button @click="deleteTableData(row)" type="danger">删除</el-button>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="缴费年度" prop="year">
                                        <template #default="{ row }">
                                            <span style="color: #f7314a"> 第 {{row.year}} 年</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="缴费状态" prop="type">
                                        <template #default="{ row }">
                                            <el-switch
                                                    @change="calculateRow(row)"
                                                    active-text="正常"
                                                    active-value="0"
                                                    inactive-text="补缴"
                                                    inactive-value="1"
                                                    v-model="row.type"
                                            ></el-switch>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="缴费档次">
                                        <template #default="{ row }">
                                            <el-select @change="calculateRow(row)" placeholder="请选择缴费档次"
                                                       v-model="row.personalPayment">
                                                <el-option label="100元" value="100"></el-option>
                                                <el-option label="120元" value="120"></el-option>
                                                <el-option label="180元" value="180"></el-option>
                                                <el-option label="240元" value="240"></el-option>
                                                <el-option label="360元" value="360"></el-option>
                                                <el-option label="480元" value="480"></el-option>
                                                <el-option label="540元" value="540"></el-option>
                                                <el-option label="600元" value="600"></el-option>
                                                <el-option label="900元" value="900"></el-option>
                                                <el-option label="1200元" value="1200"></el-option>
                                                <el-option label="1800元" value="1800"></el-option>
                                                <el-option label="3600元" value="3600"></el-option>
                                                <el-option label="4800元" value="4800"></el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="补助(资助)">
                                        <el-table-column label="村资助" prop="villageSubsidy">
                                            <template #default="{ row }">
                                                <el-input @change="calculateRow(row)"
                                                          v-model="row.villageSubsidy"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="其他资助" prop="otherSubsidy">
                                            <template #default="{ row }">
                                                <el-input @change="calculateRow(row)"
                                                          v-model="row.otherSubsidy"></el-input>
                                            </template>
                                        </el-table-column>
                                    </el-table-column>
                                    <el-table-column label="政府补贴">
                                        <el-table-column label="省补贴" prop="provinceSubsidy">
                                            <template #default="{ row }">
                                                <el-input :disabled="row.type == '1'" @change="calculateRow(row)"
                                                          v-model="row.provinceSubsidy"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="市补贴" prop="citySubsidy">
                                            <template #default="{ row }">
                                                <el-input :disabled="row.type == '1'" @change="calculateRow(row)"
                                                          v-model="row.citySubsidy"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="县补贴" prop="countySubsidy">
                                            <template #default="{ row }">
                                                <el-input :disabled="row.type == '1'" @change="calculateRow(row)"
                                                          v-model="row.countySubsidy"></el-input>
                                            </template>
                                        </el-table-column>
                                    </el-table-column>
                                    <el-table-column label="利息" prop="interest">
                                        <template #default="{ row }">
                                            <span style="color: #f7314a">  {{row.interest}} 元 </span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="年利率" prop="interestRate">
                                        <template #default="{ row }">
                                            <el-input @change="calculateRow(row)" v-model="row.interestRate"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="社会捐助及集体补助" prop="socialDonation">
                                        <template #default="{ row }">
                                            <el-input :disabled="row.type == '1'" @change="calculateRow(row)"
                                                      v-model="row.socialDonation"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="个人账户余额" prop="total">
                                        <template #default="{ row }">
                                            <span style="color: #f7314a">  {{row.total}} 元 </span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-main>
                        </el-container>
                    </el-container>
                </el-col>
                <el-col :span="8">
                    <el-container>
                        <el-header>{{form.userName != '' ? ('正在推算...' + form.userName + ' ') : ''}}发放养老待遇计算</el-header>
                        <el-container>
                            <el-main>
                                <el-form-item label="养老保险待遇 ：">
                                    <span style="font-size: 20px;color: #f7314a">{{jfForm.total}} 元</span>
                                    <el-form-item label="计算公式：">
                                        <span style="font-size: 16px;color: #f7314a">养老保险待遇 =  基础养老金（{{jfForm.basicPension}}元）  + 个人账户支出（{{(totalBalance / jfForm.jfNum).toFixed(2)}} 元） </span>
                                    </el-form-item>
                                </el-form-item>
                                <el-form-item label="基础养老金">
                                    <el-input @change="totalBalance" v-model="jfForm.basicPension"></el-input>
                                    <el-form-item label="注：">
                                        <span style="font-size: 12px">基础养老金由中央和地方政府确定标准并全额支付给符合领取条件的参保人 </span>
                                    </el-form-item>
                                </el-form-item>
                                <el-form-item label="个人账户总余额">
                                    {{totalBalance}} 元
                                </el-form-item>
                                <el-form-item label="个人账户支出">
                                    <el-select @change="getBackTime" placeholder="请选择" v-model="jfForm.jfNum">
                                        <el-option :label="'55岁退休按170个月发，每月可领'+ (totalBalance/170).toFixed(2) +'元'"
                                                   value="170"></el-option>
                                        <el-option :label="'56岁退休按164个月发，每月可领'+ (totalBalance/164).toFixed(2) +'元'"
                                                   value="164"></el-option>
                                        <el-option :label="'57岁退休按158个月发，每月可领'+ (totalBalance/158).toFixed(2) +'元'"
                                                   value="158"></el-option>
                                        <el-option :label="'58岁退休按152个月发，每月可领'+ (totalBalance/152).toFixed(2) +'元'"
                                                   value="152"></el-option>
                                        <el-option :label="'59岁退休按145个月发，每月可领'+ (totalBalance/145).toFixed(2) +'元'"
                                                   value="145"></el-option>
                                        <el-option :label="'60岁退休按139个月发，每月可领'+ (totalBalance/139).toFixed(2) +'元'"
                                                   value="139"></el-option>
                                        <el-option :label="'61岁退休按132个月发，每月可领'+ (totalBalance/132).toFixed(2) +'元'"
                                                   value="132"></el-option>
                                        <el-option :label="'62岁退休按125个月发，每月可领'+ (totalBalance/125).toFixed(2) +'元'"
                                                   value="125"></el-option>
                                        <el-option :label="'63岁退休按117个月发，每月可领'+ (totalBalance/117).toFixed(2) +'元'"
                                                   value="117"></el-option>
                                        <el-option :label="'64岁退休按109个月发，每月可领'+ (totalBalance/109).toFixed(2) +'元'"
                                                   value="109"></el-option>
                                        <el-option :label="'65岁退休按101个月发，每月可领'+ (totalBalance/101).toFixed(2) +'元'"
                                                   value="101"></el-option>
                                    </el-select>
                                    <el-form-item label="计算方式：">
                                        <span style="font-size: 12px;color: #f7314a">个人账户支出  = 总计个人账户余额 ➗ {{jfForm.jfNum}} </span>
                                    </el-form-item>
                                </el-form-item>
                            </el-main>
                        </el-container>
                    </el-container>
                    <el-container>
                        <el-header>{{form.userName != '' ? ('正在推算...' + form.userName + ' ') : ''}}个人支出回本计算</el-header>
                        <el-container>
                            <el-main>
                                <el-form-item label="个人和集体补助缴费支出总金额：">
                                    <span style="font-size: 16px;color: #f7314a"> {{totalPayment + totalJtPayment}} 元 </span>
                                </el-form-item>
                                <el-form-item label="个人缴费支出总金额：">
                                    {{totalPayment}} 元
                                </el-form-item>
                                <el-form-item label="集体补助缴费支出总金额：">
                                    {{totalJtPayment}} 元
                                </el-form-item>

                                <el-form-item label="每个月收回个人账号支出：">
                                    {{jfForm.backTotal}} 元
                                </el-form-item>
                                <el-form-item label="预算收回缴费支出时间/月：">
                                    {{jfForm.backMoth}} 个月
                                </el-form-item>
                                <el-form-item label="预算收回缴费支出时间/年：">
                                    {{jfForm.backMoth / 12}} 年
                                </el-form-item>
                            </el-main>
                        </el-container>
                    </el-container>
                    <el-container>
                        <el-header>计算历史记录</el-header>
                        <el-header>
                            <el-row>
                                <el-col :span="16">
                                    <el-input placeholder="请输入保存名称" v-model="form.userName"></el-input>
                                </el-col>
                                <el-col :span="8">
                                    <el-button @click="saveData" type="primary">保存</el-button>
                                </el-col>
                            </el-row>
                        </el-header>
                        <el-container>
                            <el-main>
                                <el-table :data="tableUserData" style="width: 100%">
                                    <el-table-column label="编号" prop="id"></el-table-column>
                                    <el-table-column label="名称" prop="userName"></el-table-column>
                                    <el-table-column label="操作" prop="total">
                                        <template #default="{ row }">
                                            <el-button @click="loadData(row)" type="primary">查 看</el-button>
                                            <el-button @click="deleteData(row)" type="danger">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-main>
                        </el-container>
                    </el-container>
                </el-col>
            </el-row>
        </el-tab-pane>
        <el-tab-pane label="常见问题" name="second">
            <el-row :gutter="20">
                <el-col v-for="guide in guideInfos" :span="8" >
                    <el-card shadow="hover" :style="{ backgroundColor: guide.color }" @click="openLink(guide.url)" :body-style="{ padding: '20px',height:'68px' }">
                        <a class="clickable-card clickable-link"><span class="guide-title">{{ guide.title }}</span></a>
                    </el-card>
                </el-col>
            </el-row>
        </el-tab-pane>
    </el-tabs>
</div>

<!-- 引入 Vue 3 -->
<script type='text/javascript' src='./js/vue.global.js'></script>
<!-- 引入 Element Plus -->
<script type='text/javascript' src='https://unpkg.com/element-plus@2.9.3/dist/index.full.js'></script>
<script>
    const {createApp, ref, computed, onMounted} = Vue;

    createApp({
        setup() {
            const form = ref({
                grade: '180',
                activeName: 'first',
                userName: '',
            });
            const jfForm = ref({
                jfNum: '139',
                basicPension: 220,// 基础养老金政府发的
                total: 0, //每月发放养老待遇金额
                backTotal: 0,
                backMoth: 0,
            });
            // 指引信息数组
            const guideInfos = ref([
                { title: '广东省人民政府关于印发《广东省城乡居民基本养老保险实施办法》的通知粤府〔2019〕105号', content: '这是指南1的内容', color: '#409EFF', url: 'http://www.gd.gov.cn/zwgk/gongbao/2020/1/content/post_3366631.html' },
            ]);

            const tableData = ref([]);
            const tableUserData = ref([]);
            const totalBalance = computed(() => {
                // 获取最后一年的个人账号总额
                let total = 0;
                total = tableData.value[tableData.value.length - 1]?.total || 0;
                // 计算养老发放
                getTotal(total);
                return total;
            });
            // 添加年度
            const addYear = () => {
                const newYear = {
                    year: tableData.value.length + 1,//缴费年限
                    type: '0',//缴费年限
                    personalPayment: form.value.grade || 0,//个人缴费
                    villageSubsidy: 0,//村资助
                    otherSubsidy: 0,//其他资助
                    provinceSubsidy: form.value.grade < 600 ? 10 : 20,//省补贴
                    citySubsidy: form.value.grade < 600 ? 10 : 20,//市补贴
                    countySubsidy: form.value.grade < 600 ? 10 : 20,//县补贴
                    interest: 0,//利息
                    interestRate: 0.017,//利率
                    socialDonation: 0,//社会捐助及集体补助
                    total: 0  // 账号余额
                };
                // 添加到表格
                tableData.value.push(newYear);
                calculateRow(newYear);
            };

            // 数值变动重新计算
            const calculateRow = (row) => {
                const personalPayment = parseFloat(row.personalPayment) || 0;
                const villageSubsidy = parseFloat(row.villageSubsidy) || 0;
                const otherSubsidy = parseFloat(row.otherSubsidy) || 0;
                // 个人档次变动 补贴需要调整
                const provinceSubsidy = row.type == '0' ? (parseFloat(row.personalPayment) < 600 ? 10 : 20) : 0;
                const citySubsidy = row.type == '0' ? (parseFloat(row.personalPayment) < 600 ? 10 : 20) : 0;
                const countySubsidy = row.type == '0' ? (parseFloat(row.personalPayment) < 600 ? 10 : 20) : 0;
                //变动当前行的省市县补贴
                row.provinceSubsidy = provinceSubsidy;
                row.citySubsidy = citySubsidy;
                row.countySubsidy = countySubsidy;

                const socialDonation = parseFloat(row.socialDonation) || 0;
                const interestRate = row.type == '0' ? (parseFloat(row.interestRate) || 0) : 0; // 补缴不算缴费补贴和利息

                // 上一年个人账号总额
                const previousTotal = tableData.value[row.year - 2]?.total || 0;

                // 计算利息的总额
                const interest = (previousTotal + personalPayment + villageSubsidy + otherSubsidy + provinceSubsidy + citySubsidy + countySubsidy + socialDonation) * interestRate;
                row.interest = interest.toFixed(2);
                const total = (parseFloat(previousTotal) + personalPayment + villageSubsidy + otherSubsidy + provinceSubsidy + citySubsidy + countySubsidy + socialDonation + interest).toFixed(2);
                row.total = total;

                //判断是否修改完数据后面还要其他年份的数据，则循环计算后面的年份数据
                if (row.year < tableData.value.length) {
                    // 循环计算后面的年份数据
                    for (let i = row.year; i < tableData.value.length; i++) {
                        calculateRow(tableData.value[i]);
                    }
                }

                // 计算回本数据
                getBackTime();
            };

            //计算每月养老待遇
            const getTotal = (totals) => {
                const totalBalanceParsed = Number(totals) || 0;
                const pensionParsed = Number(jfForm.value.basicPension) || 0;
                const jfNumParsed = Number(jfForm.value.jfNum) || 1; // 避免除零

                const personalAccountSpending = (totalBalanceParsed / jfNumParsed).toFixed(2);

                const total = pensionParsed + Number(personalAccountSpending);

                jfForm.value.total = total;
            };

            // 重置数据
            const resetData = () => {
                tableData.value = [];
                jfForm.value = {
                    jfNum: '139',
                    basicPension: 220,// 基础养老金政府发的
                    total: 0, //每月发放养老待遇金额
                    backTotal: 0,
                    backMoth: 0,
                };
                form.value = {
                    grade: '180',
                    activeName: 'first',
                };
            };

            // 计算个人总缴费金额
            const totalPayment = computed(() => {
                return tableData.value.reduce((sum, row) => sum + parseFloat(row.personalPayment || 0), 0);
            });

            // 计算集体资助总缴费金额
            const totalJtPayment = computed(() => {
                return tableData.value.reduce((sum, row) => sum + parseFloat(row.socialDonation || 0), 0);
            });

            // 获取回本时间
            const getBackTime = () => {
                const totalPaymentParsed = Number(totalPayment.value) || 0; // 计算个人总缴费金额
                const totalJtPaymentParsed = Number(totalJtPayment.value) || 0; // 计算集体总缴费金额
                const jfNumParsed = Number(jfForm.value.jfNum) || 0; //计发月数
                const totalBalanceParsed = Number(totalBalance.value) || 0; // 账号总额
                if (jfNumParsed === 0) {
                    return 0; // 避免除以零
                }
                // 每月可领自己交的钱
                const personalAccountSpending = (totalBalanceParsed / jfNumParsed).toFixed(2);
                jfForm.value.backTotal = personalAccountSpending;
                jfForm.value.backMoth = ((totalPaymentParsed + totalJtPaymentParsed) / Number(personalAccountSpending)).toFixed(2);
            };

            // 保存数据到浏览器缓存
            const saveData = () => {
                if (!form.value.userName.trim()) {
                    alert("用户名不能为空");
                    return;
                }
                const userInfo = {
                    id: Date.now().toString(),
                    userName: form.value.userName,
                    form: form.value,
                    jfForm: jfForm.value,
                    tableData: tableData.value,
                };
                // 先从缓存中读取现有数据
                let existingData = [];
                try {
                    const cachedData = localStorage.getItem('pension-retirement-tool-data');
                    if (cachedData) {
                        existingData = JSON.parse(cachedData);
                    }
                } catch (error) {
                    console.error("解析缓存数据失败:", error);
                }

                // 将新用户数据添加到现有数据中
                existingData.push(userInfo);

                // 保存更新后的数据到缓存
                try {
                    localStorage.setItem("pension-retirement-tool-data", JSON.stringify(existingData));
                } catch (error) {
                    console.error("保存数据失败:", error);
                }

                form.value.userName = ''; // 清空输入框

                tableUserData.value = existingData;
            };

            // 删除数据
            const deleteData = (row) => {
                tableUserData.value = tableUserData.value.filter(item => item.id !== row.id);
                // 先清空
                localStorage.removeItem("pension-retirement-tool-data");
                try {
                    // 使用深拷贝来避免循环引用
                    localStorage.setItem("pension-retirement-tool-data", JSON.stringify(JSON.parse(JSON.stringify(tableUserData.value))));
                } catch (error) {
                    console.error("保存数据失败:", error);
                }
            };

            // 从缓存中读取数据
            const loadData = (row) => {
                form.value = row.form;
                form.value.userName = row.userName;
                jfForm.value = row.jfForm;
                tableData.value = row.tableData;
            };

            // 跳转指引
            const openLink  = (url) => {
                window.open(url, '_blank');
            };

            // 初始化数据时从缓存中读取
            onMounted(() => {
                try {
                    const cachedData = localStorage.getItem('pension-retirement-tool-data');
                    if (cachedData) {
                        tableUserData.value = JSON.parse(cachedData);
                        console.log("从缓存中读取的数据：", tableUserData.value)
                    } else {
                        tableUserData.value = [];
                    }
                } catch (error) {
                    console.error("解析缓存数据失败:", error);
                    tableUserData.value = [];
                }
            });

            // 删除个人账户收入计算表的数据
            const deleteTableData = (row) => {
                tableData.value = tableData.value.filter(item => item.year !== row.year);
                // 循环计算后面的年份数据
                for (let i = 0; i < tableData.value.length; i++) {
                    tableData.value[i].year = i + 1;
                }
                // 不是删除第一行才需要计算
                if(tableData.value.length > 0 ){
                    calculateRow(tableData.value[0]);
                }
            };

            return {
                form,
                jfForm,
                guideInfos,
                tableData,
                tableUserData,
                totalBalance,
                totalPayment,
                totalJtPayment,
                saveData,
                deleteData,
                loadData,
                addYear,
                calculateRow,
                getTotal,
                resetData,
                getBackTime,
                openLink,
                deleteTableData
            };
        }
    })
        .use(ElementPlus)
        .mount('#app');
</script>
</body>
</html>
